package com.shiro.demo.shiro;

import com.shiro.demo.utils.MD5Util;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

/**
 * @author tracyclock 2017-12-08
 * shiro自定义密码验证
 */
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {

    @Override
    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {
        //传入的参数进行类型转换
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        SimpleAuthenticationInfo simpleInfo = (SimpleAuthenticationInfo)info;
        //获取传入的盐
        String salt = new String(simpleInfo.getCredentialsSalt().getBytes());

        //tokenCredentials，用户输入的密码经过加密后的密码   accountCredentials：传入的数据库密码
        Object tokenCredentials = encrypt(String.valueOf(token.getPassword()),salt);
        Object accountCredentials = getCredentials(info);
        //将密码加密与系统加密后的密码校验，内容一致就返回true,不一致就返回false
        return equals(tokenCredentials, accountCredentials);
    }

    //自定义加密方法，将传进来密码用MD5加盐加密
    private String encrypt(String password,String salt) {
        return MD5Util.getMD5CodeBySalt(password,salt);
    }

}
